<template>
	<div class="search-page">
		<el-card class="search-wapper">
			<div style="display: flex;align-items: center;">
				<el-input style="margin-right: 14px" clearable v-model="from.keyword"/>
				<el-button type="primary" @click="search">搜索</el-button>
			</div>

			<div style="display: flex; align-items: center; justify-content: space-between; width: 100%;" v-if="historyKeywords.length != 0">
				<div class="search-history" ref="historyRef">
					<div class="history-item" v-for="item in historyKeywords" @click="historyClick(item)">{{item}}</div>
				</div>
				<el-button type="primary" style="margin-left: 14px;" size="small" @click="clearHistory">清除历史</el-button>
			</div>
		</el-card>
		<el-card class="search-wapper" style="flex: 1; margin-top: 20px">
			<el-empty v-if="list.length === 0" description="暂无内容!"></el-empty>

			<template v-else>
				<el-card class="topic-item" v-for="item in list" @click="toDetail(item)">
					<div style="margin-bottom: 8px; font-size: 18px; font-weight: 600;">{{item.title}}</div>
					<div style="display: flex; align-items: center; justify-content: space-between;">
						<div>
							<el-text style="margin-right: 20px">{{item.board_name}}</el-text>
							<el-text>{{item.author.username}} 发布于: {{getTime(item.created_at)}}</el-text>
						</div>
						<div>
							<el-text> 点赞 {{item.like_count}} </el-text>
							<el-text> 浏览 {{item.view_count}}</el-text>
						</div>
					</div>
				</el-card>
				<div style="display: flex; justify-content: center;">
					<el-pagination background layout="prev, pager, next" :total="total" @current-change="currentChange"/>
				</div>
			</template>
		</el-card>
	</div>
</template>
<script setup>
import {topic_list} from '/@/api/forum'
import {ref, onMounted, nextTick, onUnmounted} from 'vue'
import dayjs from 'dayjs'
import {useRouter} from 'vue-router'
import handleScroll from '/@/utils/handleScroll.js'

const router = useRouter()
const toDetail = (item)=> {
	window.localStorage.setItem('topicDetail', JSON.stringify(item))
	router.push({
		path: `/topicdetail`
	})
}

const getTime = (time)=> {
	return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

const from = ref({
	keyword: '',
	board_id: '',
	page: 1,
	page_size: 10
})
const historyKeywords = ref([])


const list = ref([])
const total = ref(0)
const getList = async ()=> {
	const res = await topic_list(from.value)
	if(from.value.keyword){
		const str = `${from.value.keyword},` + historyKeywords.value.join(',')
		window.localStorage.setItem('forum_search_history', str)
		historyKeywords.value = [...new Set(str.split(',').filter(item => !!item))]
	}
	list.value = res.data.topics
	total.value = res.data.total

}

const currentChange = page=> {
	from.value.page = page
	getList()
}

const search = ()=> {
	list.value = []
	from.value.page = 1
	getList()
}

const historyClick = keyword=> {
	from.value.keyword = keyword
	search()
}


const clearHistory = ()=> {
	historyKeywords.value = []
	window.localStorage.setItem('forum_search_history', '')
}


//给顶部搜索历史增加横向拖动事件
const historyRef =ref(null)
let isDragging = false;
let startX = null;
let scrollLeft = null;
const addHistoryDragging = ()=> {

	nextTick(()=> {
		if(!historyRef.value){
			return
		}
		historyRef.value.addEventListener('mousedown', (e) => {
			isDragging = true;
			startX = e.pageX - historyRef.value.offsetLeft;
			scrollLeft = historyRef.value.scrollLeft;
		});
		// 鼠标移动事件
		historyRef.value.addEventListener('mousemove', (e) => {
			if (!isDragging) return;
			e.preventDefault();
			const x = e.pageX - historyRef.value.offsetLeft;
			const walk = (x - startX) * 2; // 控制滚动速度
			historyRef.value.scrollLeft = scrollLeft - walk;
		});
		// 鼠标松开事件
		historyRef.value.addEventListener('mouseup', () => {
			isDragging = false;
		});
		// 鼠标移出事件
		historyRef.value.addEventListener('mouseleave', () => {
			isDragging = false;
		});
		historyRef.value.addEventListener('mousedown', (e) => {
			isDragging = true;
			startX = e.pageX - historyRef.value.offsetLeft;
			scrollLeft = historyRef.value.scrollLeft;
		});

	})
}

onMounted(()=> {
	const list = localStorage.getItem('forum_search_history')
	if(list){
		historyKeywords.value = [... new Set(list.split(',').filter(item => !!item))]
	}
	addHistoryDragging()

	let temp_params = localStorage.getItem('search_temp_params')
	if(temp_params){
		temp_params = JSON.parse(temp_params)
		from.value.keyword = temp_params?.keyword || ''
		from.value.board_id = temp_params?.board || ''
		from.value.page = 1
	}
	window.localStorage.removeItem('search_temp_params')
	getList()


})

onUnmounted(() => {
	// 组件卸载时解绑滚动事件
	window.removeEventListener('scroll', handleScroll);
});


</script>
<style scoped lang="scss">
.search-page{
	width: 100%;
	min-height: calc(100vh - 60px);
	padding: 20px;
	display: flex;
	flex-direction: column;
	.search-wapper{
		width: 60%;
		margin: 0 auto;
		.search-history{
			flex: 1;
			display: flex;
			flex-wrap: nowrap;
			overflow-x: auto;
			height: 40px;
			align-items: center;
			.history-item{
				height: 30px;
				padding: 0 8px;
				border: 1px solid #E4E7ED;
				color: #606266;
				border-radius: 14px;
				font-size: 12px;
				cursor: pointer;
				margin-right: 14px;
				display: flex;
				align-items: center;
				justify-content: center;
				-webkit-user-select: none;
				-moz-user-select: none;
				-ms-user-select: none;
				user-select: none;
			}

		}
		.search-history::-webkit-scrollbar {
			height: 2px;
		}
		.search-history::-webkit-scrollbar-thumb {
			background-color: #888;
			border-radius: 4px;
		}
		.search-history::-webkit-scrollbar-thumb:hover {
			background-color: #555;
		}
		.topic-item{
			margin-bottom: 14px;
		}
	}
}
</style>
